//
//  DBHeartRate.m
//  CareRingApp
//
//  Created by Linktop on 2022/6/7.
//

#import "DBHeartRate.h"
#import "SdkInnerHeader.h"
#import "DBHistoryDataSr03.h"
#import "LTSRingSDK.h"
//NSString * const TABLE_NM_HEART = @"table_heartrate";

const float HR_LOW = 50;
const float HR_HIGH = 175;


@implementation DBHeartRate



+(void)queryBy:(NSString * _Nonnull)macAddress
         Begin:(NSDate *)beginDate
           End:(NSDate *)endDate
OrderBeTimeDesc:(BOOL)isDesc
      Cpmplete:(void(^)(NSMutableArray<DBHeartRate *> *results,
                        NSNumber *maxHr, NSNumber *minHr,
                        NSNumber *avgHr))cmpBlk
{
    
    [DBHistoryDataSr03 queryBy:macAddress Begin:beginDate End:endDate OrderBeTimeDesc:isDesc Cpmplete:^(NSMutableArray<DBHistoryDataSr03 *> * _Nonnull results) {
        
        NSMutableArray<DBHeartRate *> *heartRes = [NSMutableArray new];
        
        NSNumber *maxHr, *minHr, *avgHr;
        NSInteger count = 0;
       
        float hr_low = LTSRingSDK.instance.heartrateFilterLowerLimit;
        float hr_high = HR_HIGH;
        
        for (DBHistoryDataSr03 *hisObj in results) {
           
            if (hisObj.deviceModifyHeartRate.intValue >= hr_low && hisObj.deviceModifyHeartRate.intValue <= hr_high) {
                DBHeartRate *heartModel = [[DBHeartRate alloc]init];
                
                heartModel.value = hisObj.deviceModifyHeartRate;
                heartModel.time = [NSDate dateWithTimeIntervalSince1970:hisObj.time.doubleValue];
                heartModel.macAddress = hisObj.macAddress;
                heartModel.isSportMode = hisObj.isSportMode;
                heartModel.battery = hisObj.battery;
                [heartRes addObject:heartModel];
                
                if (maxHr == nil) { // 最大
                    maxHr = hisObj.deviceModifyHeartRate;
                } else if (maxHr.intValue < hisObj.deviceModifyHeartRate.intValue) {
                    maxHr = hisObj.deviceModifyHeartRate;
                }
                
                if (minHr == nil) { // 最小
                    minHr = hisObj.deviceModifyHeartRate;
                } else if (minHr.intValue > hisObj.deviceModifyHeartRate.intValue) {
                    minHr = hisObj.deviceModifyHeartRate;
                }
                
                if (hisObj.deviceModifyHeartRate) { // 平均
                    avgHr = @(avgHr.floatValue +hisObj.deviceModifyHeartRate.floatValue);
                    count++;
                }
                
            }
           
        }
        if (count > 0) {
            avgHr = @(avgHr.floatValue / count);
        }
        
        if (cmpBlk) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cmpBlk(heartRes, maxHr, minHr, avgHr);
            });
        }
        
    }];
    
    

    
}



//+(void)queryForSleepBy:(NSString * _Nonnull)account Begin:(NSDate *)beginDate End:(NSDate *)endDate OrderBeTimeDesc:(BOOL)isDesc
//         CallBackQueue:(dispatch_queue_t)queue
//              Cpmplete:(void(^)(NSMutableArray<NSMutableDictionary *> *results))cmpBlk
//{
//    if (queue == nil) {
//        queue = dispatch_get_main_queue();
//    }
//    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
//
//        NSMutableArray<NSMutableDictionary *> *results = [NSMutableArray new];
//
//        NSString *sql =  [NSString stringWithFormat:@"SELECT rowid , * FROM %@ WHERE account = ? AND time BETWEEN ? AND ? ORDER BY time %@", TABLE_NM_HEART, isDesc ? @"DESC" : @"ASC"];
//        FMResultSet *rs = [db executeQuery:sql, account, beginDate, endDate];
//        while ([rs next]) {
//            //NSString * const SLEEP_KEY_TIME = @"time";
////            NSString * const SLEEP_KEY_HR = @"hr";
//            NSMutableDictionary *dict = [NSMutableDictionary new];
//            dict[@"time"] = @([rs doubleForColumn:@"time"]);
//            dict[@"hr"] = @([rs doubleForColumn:@"value"]);
//            [results addObject:dict];
//        }
//        [rs close];
//
//        if (cmpBlk) {
//            dispatch_async(queue, ^{
//                cmpBlk(results);
//            });
//        }
//
//    }];
//}


//+(void)queryMutiDataGroupHours:(NSString * _Nonnull)account DayDate:(NSDate *)dayDate   Cpmplete:(void(^)(NSMutableArray<NSDictionary *> * res) )cmpBlk
//{
////    [super queryMutiDataGroupHours:account DayDate:dayDate TableName:TABLE_NM_HEART Cpmplete:cmpBlk];
//}


//-(void)insert:(void(^_Nullable)(BOOL succ))complete
//{
//    [super insertBy:TABLE_NM_HEART CMP:complete];
//
//
//}

/// 查询账号关联的数据的最大时间戳
/// @param account 账号
/// @param cmpBlk 回调
//+(void)queryMaxTime:(NSString * _Nonnull)account Cpmplete:(void(^)(NSNumber * _Nullable maxTimeStamp) )cmpBlk
//{
//    [super queryMaxTime:account TableName:TABLE_NM_HEART Cpmplete:cmpBlk];
//}

//+(void)deleteAll {
//    [super deleteAll:TABLE_NM_HEART];
//}

#pragma mark -- HMPdfShareProtoal
//- (NSArray<NSString *> *)pdfShowValuerStrings:(NSInteger)index {
//    NSArray *resArray = nil;
//    NSString *noStr = [NSString stringWithFormat:@"%ld", index];
//    
//    NSString *dateStr = [self.time formatPdfShareTime:_L(L_PDF_TIME_FORMAT)];
//   
//    NSString *hrStr = [NSString stringWithFormat:@"%@%@", self.value, _L(L_PDF_UNIT_HR)];
//    
//    resArray = @[noStr, dateStr,  hrStr];
//    return resArray;
//}


///
/// - Parameter motion: 运动计数
-(BOOL)sleepHeartRateFix:(float)motion {
    BOOL isFix = YES;
    NSNumber *origin = self.value;
    if (motion < 60) {
        if (self.value.floatValue >= 190) {
//            this.div(2.3).toInt()
            self.value = @((int)(self.value.floatValue / 2.3));
        } else if (self.value.floatValue >= 170) {
//            this.div(2.2).toInt()
            self.value = @((int)(self.value.floatValue / 2.2));

        } else if (self.value.floatValue >= 150) {
//            this.div(1.9).toInt()
            self.value = @((int)(self.value.floatValue / 1.9));

        } else if (self.value.floatValue > 130) {
//            this.div(1.7).toInt()
            self.value = @((int)(self.value.floatValue / 1.7));

        } else if (self.value.floatValue > 120) {
//            this.div(1.5).toInt()
            self.value = @((int)(self.value.floatValue / 1.5));

        } else if (self.value.floatValue > 110) {
//            this.div(1.4).toInt()
            self.value = @((int)(self.value.floatValue / 1.4));

        } else {
            isFix = NO;
        }
    } else {
        isFix = NO;
    }
    if (isFix) {
        DebugNSLog(@"同步修正心率 原=%@, 修正=%@, motion=%f",origin, self.value, motion);
    }
    return isFix;
}

/// 计算静息心率
/// - Parameters:
///   - begin: 开始时间
///   - end: 结束时间
///   - account: 账号
///   - cmpBlk: 回调
//+(void)restingHeartRateForm:(NSDate *)begin End:(NSDate *)end Account:(NSString *)account CMP:(void(^)(NSNumber * _Nullable restingHr) )cmpBlk
//{
//    [self queryBy:account Begin:begin End:end OrderBeTimeDesc:YES Cpmplete:^(NSMutableArray<DBHeartRate *> * _Nonnull results) {
//        
//       
//        __block double all = 0;
//        double average_1 = 0;
//        if (results.count) {
//            [results enumerateObjectsUsingBlock:^(DBHeartRate * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                all += obj.value.doubleValue;
//            }];
//            average_1 = all / results.count;  // 取第一次平均值
//            // 上下去除 20%
//            double high = average_1 * (1.f + 0.2);
//            double low = average_1 * (1.f - 0.2);
//            __block double all_2 = 0;
//            __block int count = 0;
//            [results enumerateObjectsUsingBlock:^(DBHeartRate * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                if (obj.value.doubleValue > low && obj.value.doubleValue > high) {
//                    all_2 += obj.value.doubleValue;
//                    count++;
//                }
//                
//            }];
//            
//            double resHr = all_2 / count;
//            if (cmpBlk) {
//                cmpBlk(@(resHr));
//            }
//        } else {
//            if (cmpBlk) {
//                cmpBlk(nil);
//            }
//        }
//        
//        
//    }];
//    
//}

@end
